"""
@author: zjc
@file: user.py
@time: 2023/3/13 20:17
"""
from wtforms import Form, StringField
from wtforms.validators import DataRequired, Regexp, ValidationError
from model.userdb.userinfo import User
from werkzeug.security import check_password_hash

class UserForm(Form):
    username = StringField(validators=[DataRequired()])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}',
                                                    message="密码不符合要求")])
    def validate_username(self, value):
        if User.query.filter_by(username = value.data).first():
            raise ValidationError("用户名已存在")

class LoginForm(Form):
    username = StringField(validators=[DataRequired()])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}',
                                                    message="密码不符合要求")])

    def validate(self):
        super().validate()
        if self.errors:
            return False
        user = User.query.filter_by(username =self.username.data).first()
        if user and check_password_hash(user.password, self.password.data):
            return user
        else:
            raise ValidationError("用户名错误,验证失败！")
